﻿using DBUtil.Attributes;
using NUnit.Framework;
using Shouldly;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace Test.MySql.ColumnTypeTests
{
    [TestFixture]
    internal class ColumnTypesTestsByteArr : TestBase
    {
        #region model
        [Table("test")]
        public class Person
        {
            [PrimaryKey,Identity]
            [Column("id")]
            public int Id { get; set; }

            public byte[] Image { get; set; }
        }
        #endregion

        [SetUp]
        public void SetUp()
        {
            DropTableIfExist("test");
            db.ExecuteSql("""create table test(id int auto_increment primary key,image blob)""");
            db.ExecuteSql("""
                insert into test(image) values(0xE4BDA0E5A5BD2C68656C6C6F21);
                """);
        }

        [Test]
        public void TestInsert()
        {
            var insert = db.Insert<Person>().SetEntity(new Person
            {
                Image = Encoding.UTF8.GetBytes("你好,hello!")
            });
            var sql = insert.ToSql();
            sql.ShouldBe("""insert into `test`(`Image`) values(0xE4BDA0E5A5BD2C68656C6C6F21);""");
            var p = insert.ExecuteInserted();
            Encoding.UTF8.GetString(p.Image).ShouldBe("你好,hello!");
        }

        [Test]
        public void TestSelect()
        {
            var select = db.Select<Person>().Where(i => i.Image != null);
            var sql = select.ToSqlList();
            sql.ShouldBe("""
                select t.`id` `Id`,t.`Image`
                from `test` t
                where t.`Image` is not null;
                """);
            var p = select.FirstOrDefault();
            Encoding.UTF8.GetString(p.Image).ShouldBe("你好,hello!");

            var select2 = db.Select<Person>().Where(i => i.Image.Length > 0);
            var sql2 = select2.ToSqlList();
            sql2.ShouldBe("""
                select t.`id` `Id`,t.`Image`
                from `test` t
                where length(t.`Image`) > 0;
                """);
            var p2 = select2.FirstOrDefault();
            Encoding.UTF8.GetString(p2.Image).ShouldBe("你好,hello!");
        }

        [Test]
        public void TestUpdate()
        {
            var bs = Encoding.UTF8.GetBytes("hello world!");
            var update = db.Update<Person>().SetEntity(new Person { Id = 1, Image = bs });
            var sql = update.ToSql();
            sql.ShouldBe("""
                update `test` set
                    `Image` = 0x68656C6C6F20776F726C6421
                where `id` = 1;
                """);
            var r = update.ExecuteAffrows();
            r.ShouldBe(1);
            var p = db.Select<Person>().Where(i => i.Id == 1).FirstOrDefault();
            Encoding.UTF8.GetString(p.Image).ShouldBe("hello world!");
        }
    }
}
